import {onMounted, onUnmounted, reactive, ref} from 'vue';
import {useMessage} from '/@/hooks/web/useMessage';
import {TaskCode} from '/@/api/sys/model/msgPushModel';
import {sendUserVerifyMessage} from '/@/api/common/verify.api';
import {useModal} from '/@/components/Modal';

// 倒计时60s
const TIME_COUNT  = 60

export interface VerifyProps {
  taskCode: TaskCode;
  bizType?: string;
  setFieldsValue?: <T>(values: T) => Promise<void>;
  api?: Function;
  apiParams?: Object
}

export const useVerify = (props : VerifyProps) => {
  const timer = ref<any>()
  const count = ref(TIME_COUNT)
  const { createMessage } = useMessage();
  const disabled = ref(false)
  const verifyInfo = reactive<any>({})
  const butName = ref('点击获取')
  const [registerManMachineVerifyModal, { openModal: openManMachineVerifyModal }] = useModal();

  verifyInfo.taskCode = props.taskCode
  verifyInfo.bizType = props.bizType
  onMounted(async () => {
    
  })

  onUnmounted(() => {
    clearInterval(timer.value);
    timer.value = null;
  })


  const handleSend = async () => {
    openManMachineVerifyModal(true, {})
  }

  const handleManMachineVerifySuccess = async (data) => {
    verifyInfo.uuid = data.uuid
    verifyInfo.imageCaptcha = data.imageCaptcha

    if (!disabled.value) {
      clearInterval(timer.value);
      timer.value = null;
      disabled.value = true
      timer.value = setInterval(() => {
        if (count.value > 0 && count.value <= TIME_COUNT) {
          count.value = count.value - 1;
          butName.value = count.value + 'S'
        } else {
          butName.value = '点击获取'
          count.value = TIME_COUNT
          disabled.value = false;
          clearInterval(timer.value);
          timer.value = null;
        }
      }, 1000);
      
      if (props.api) {
        await props.api({
          bizType: props.bizType,
          taskCode: props.taskCode,
          ...props.apiParams,
          ...verifyInfo
        })
      } else {
        await sendUserVerifyMessage({
          bizType: props.bizType,
          taskCode: props.taskCode,
          ...props.apiParams,
          ...verifyInfo
        })
      }
  
      createMessage.success(`验证码已发送, 请注意查收`)
    }
  }

  return {
    butName, disabled, verifyInfo, handleSend, registerManMachineVerifyModal,
    handleManMachineVerifySuccess
  }
}
